package com.huatech.cloud.filter;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.druid.filter.FilterAdapter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.proxy.jdbc.DataSourceProxy;
import com.huatech.cloud.config.EncryptorTools;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class JasyptDataSourceFilter extends FilterAdapter {
    
	@Autowired(required = false)
	private StringEncryptor stringEncryptor;
	 
	@Override
    public void init(DataSourceProxy dataSourceProxy) {
		if (!(dataSourceProxy instanceof DruidDataSource)) {
            log.error("ConfigLoader only support DruidDataSource");
            return;
        }

        DruidDataSource dataSource = (DruidDataSource) dataSourceProxy;
        // 判断是否需要解密，如果需要就进行解密行动
        dataSource.setUsername(decrypt(dataSource.getUsername()));
        dataSource.setPassword(decrypt(dataSource.getPassword()));
    }
	

	public String decrypt(String ecryptValue) {
		return EncryptorTools.decrypt(stringEncryptor, ecryptValue);
	}
	
}
